package com.oto.web.resource;

import java.io.StringReader;
import java.util.Collection;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.LogType;
import com.oto.Result;
import com.oto.model.AccountDO;
import com.oto.model.FlowDO;
import com.oto.model.LogDO;
import com.oto.model.PackDO;
import com.oto.util.JAXBUtils;
import com.oto.web.model.Message;
import com.oto.web.model.XmlAccount;
import com.oto.web.model.XmlFlow;
import com.oto.web.model.XmlPack;

/**
 * @author xueqiang.mi
 * @since 2010-12-19
 */
@Path("/mobile")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MobileResource extends BaseResource {

	@GET
	@Path("bind")
	@Produces("text/plain;charset=UTF-8")
	public String bind(@QueryParam(value = "imei") String imei, @QueryParam(value = "name") String name) {
		accountService.bind(name, imei);
		return Constants.STATUS_DONE;
	}

	@GET
	@Path("search/frid")
	@Produces("text/plain;charset=UTF-8")
	public String searchFrid(@QueryParam(value = "name") String name) {
		if (!name.contains("@")) {
			name += "@gmail.com";
		}
		AccountDO account = accountService.get(name);
		if (account == null) {
			return "null";
		} else {
			return account.getName();
		}
	}

	/**
	 *TODO used now
	 * 
	 * @param key
	 * @return message
	 */
	@GET
	@Path("search/pack")
	@Produces("application/xml;charset=UTF-8")
	public String searchPack(@QueryParam(value = "key") String key) {
		LogDO log = new LogDO(LogType.SEARCH_MOBILE, key); // log
		Collection<String> keys = searchService.parse(key);
		if (keys.isEmpty()) {
			log.setResult(Result.EMPTY_PARSE);
		}

		List<PackDO> objs = searchService.search(PackDO.class, keys, Constants.MED_SIZE);
		if (objs.isEmpty()) {
			log.setResult(Result.EMPTY_RESULT);
		} else {
			log.setResult(Result.DONE);
		}
		messageService.store(log);
		return JAXBUtils.writeMessageFromPacks(objs);
	}

	@GET
	@Path("search")
	@Produces("application/xml;charset=UTF-8")
	public String searchPhone(@QueryParam(value = "key") String key) {
		LogDO log = new LogDO(LogType.SEARCH_MOBILE, key); // log

		Collection<String> keys = searchService.parse(key);
		if (keys.isEmpty()) {
			log.setResult(Result.EMPTY_PARSE);
		}

		List<FlowDO> flows = searchService.search(FlowDO.class, keys, Constants.MED_SIZE);
		if (flows.isEmpty()) {
			log.setResult(Result.EMPTY_RESULT);
		} else {
			log.setResult(Result.DONE);
		}
		messageService.store(log);
		return JAXBUtils.writeMessageFromFlows(flows);
	}

	@POST
	@Path("share")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain;charset=UTF-8")
	public String share(@FormParam(value = "data") String data) {
		if (StringUtils.isEmpty(data)) {
			return Constants.STATUS_ERROR + " 消息内容不可以为空!";
		}
		messageService.store(LogType.SHARE, data, Result.DONE); // log

		// 解析消息
		StringReader reader = new StringReader(data);
		Message msg = JAXBUtils.unmarshal(Constants.JAXB_CONTEXT_PATH, reader);

		// 处理消息
		XmlAccount from = msg.getFromUser();
		String userName = from == null ? Constants.DEFAULT_ANONYMOUS_USER : from.getName();

		List<XmlAccount> toList = msg.getToUsers();

		if (msg.getPacks().isEmpty()) {
			return Constants.STATUS_ERROR + " 消息内容中缺少Pack数据!";
		}

		XmlPack xPack = msg.getPacks().get(0);
		PackDO pack = packService.getOrCreate(xPack.getName(), userName);

		for (XmlFlow xFlow : xPack.getFlows()) {
			FlowDO f = new FlowDO();
			f.setName(xFlow.getName());
			f.setType(xFlow.getType());
			f.setContent(xFlow.getContent());
			f.setPackId(pack.getId());
			f.setOwner(userName);
			for (XmlAccount u : toList) {
				f.getUsers().add(u.getName());
			}
			flowService.add(f);

			// 将flow push给所有toList中的用户
			accountService.pushFlow(toList, f);
		}
		return Constants.STATUS_OK;
	}

	@GET
	@Path("sync")
	@Produces("application/xml;charset=UTF-8")
	public String sync(@QueryParam("user") String user) {
		List<FlowDO> flows = flowService.getSyncFlows(user);
		return JAXBUtils.writeMessageFromFlows(flows);
	}
}
